package cn.hzking.gjmall.activitys.order;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.activitys.MainActivity;
import cn.hzking.gjmall.activitys.my.MyOrderActivity;
import cn.hzking.gjmall.app.Gjmall;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.OrderIdBean;
import cn.hzking.gjmall.bean.PayBean;
import cn.hzking.gjmall.bean.PayMessageBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.utils.CheckInstallApp;
import cn.hzking.gjmall.utils.Logger;
import cn.hzking.gjmall.utils.OnClickEvent;
import cn.hzking.gjmall.utils.SPUtils;
import cn.hzking.gjmall.utils.UIUtils;
import cn.hzking.gjmall.view.SimpleOptionView;

public class PaySuccessActivity extends ColorStatuBarActivity {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.btn_1)
    TextView btn1;
    @Bind(R.id.btn_2)
    TextView btn2;
    private boolean isnext;//是否有第二个订单需要支付
    private String nextSkuIds;
    private String nextnums;
    private IWXAPI api;
    private int groupId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pay_success);
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        simpleTileView.setTitle("支付成功");
        Intent intent = getIntent();
        isnext = intent.getBooleanExtra("isnext", false);
        nextSkuIds = intent.getStringExtra("nextSkuIds");
        nextnums = intent.getStringExtra("nextnums");
        api = WXAPIFactory.createWXAPI(this, Gjmall.getWxAppId());
        if (isnext) {
            btn1.setText("支付下一单");
        } else {
            btn1.setText("再逛逛");
        }
        simpleTileView.setLeftClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                EventBus.getDefault().post("goHome");
                Intent intent1 = new Intent(PaySuccessActivity.this, MainActivity.class);
                startActivity(intent1);
            }
        });

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        isnext = false;
        btn1.setText("再逛逛");

    }

    @OnClick(R.id.btn_1)
    public void pay(View view) {
        if (isnext) {//如果是支付下一单的话
            getOrderId();
        } else {
            EventBus.getDefault().post("goHome");
            EventBus.getDefault().post("错误返回");
            Intent intent1 = new Intent(PaySuccessActivity.this, MainActivity.class);
            startActivity(intent1);
        }
    }
    @OnClick(R.id.btn_2)
    public void seeorder(View view) {
        Intent intent = new Intent(PaySuccessActivity.this, MyOrderActivity.class);
        intent.putExtra("fragmentId",2);
        startActivity(intent);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //生成订单
    private void getOrderId() {
        HashMap<String, String> parms = new HashMap<>();
        parms.put("itemSkuIds", nextSkuIds);
        parms.put("numbers", nextnums);
        parms.put("paymethod", "WX_MP_PAY");
        parms.put("addressId", SPUtils.getAddressId(this));
        RetrofitFactory.getInstant().API()
                .getOrderId(parms)
                .compose(this.<OrderIdBean>setThread())
                .subscribe(new BaseObserver<OrderIdBean>(this, true, true) {
                    @Override
                    protected void onSuccees(OrderIdBean orderIdBean) throws Exception {

                        //成功的话就请求支付的id
                        groupId = orderIdBean.getData().getOrderPayGroups().get(0).getGroupId();
                        payWx(String.valueOf(groupId));

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        Logger.e(e.getMessage());

                    }

                    @Override
                    protected void onCodeError(OrderIdBean orderIdBean) throws Exception {
                        super.onCodeError(orderIdBean);
                        String errorMsg = orderIdBean.getErrorMsg();
                        //错误提示对话框
                        createTishiDialog(errorMsg).show();

                    }
                });

    }


    public Dialog createTishiDialog(String textString) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.dialog_sureorder_tishi, null);// 得到加载view
        TextView textView = v.findViewById(R.id.sureorder_text);
        textView.setText(String.valueOf(textString));
        final Dialog customDialog = new Dialog(this, R.style.dialog_1);// 创建自定义样式dialog
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.setCancelable(false);
        customDialog.setContentView(v);
        v.findViewById(R.id.sure).setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                EventBus.getDefault().post("错误返回");
                finish();


            }
        });


        return customDialog;
    }

    //微信支付
    private void payWx(String orderGroupId) {
        RetrofitFactory.getInstant().API()
                .payWx(orderGroupId)
                .compose(this.<PayBean>setThread())
                .subscribe(new BaseObserver<PayBean>(this, true, true) {
                    @Override
                    protected void onSuccees(PayBean payBean) throws Exception {
                        if (payBean != null) {
                            PayBean.DataBean data = payBean.getData();
                            if (data != null) {
                                PayBean.DataBean.SignPackageBean signPackage = data.getSignPackage();
                                if (signPackage != null) {
                                    PayReq req = new PayReq();
                                    req.appId = signPackage.getAppId();
                                    req.partnerId = signPackage.getPartnerId();
                                    req.prepayId = signPackage.getPrepayid();
                                    req.packageValue = signPackage.getPackageX();
                                    req.nonceStr = signPackage.getNonceStr();
                                    req.timeStamp = signPackage.getTimeStamp();
                                    req.sign = signPackage.getPaySign();
                                    req.extData = "app data";
                                    if (CheckInstallApp.isWeixinAvilible(Gjmall.getApplicationContext())) {
                                        EventBus.getDefault().postSticky(new PayMessageBean(nextSkuIds, nextnums, "", "", false,String.valueOf(groupId)));
                                        api.sendReq(req);
                                        UIUtils.showToast(PaySuccessActivity.this, "正在调起支付", Toast.LENGTH_SHORT);
                                    } else {
                                        UIUtils.showToast(PaySuccessActivity.this, "请安装微信", Toast.LENGTH_SHORT);
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }
                });

    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        EventBus.getDefault().post("goHome");
        Intent intent1 = new Intent(PaySuccessActivity.this, MainActivity.class);
        startActivity(intent1);
    }
}
